﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

#if !SILVERLIGHT
namespace UIT.WPF.Converters
#else
namespace UIT.Silverlight.Converters
#endif
{
    public class BrushConverter : IValueConverter
    {
        private System.Windows.Media.Brush defaultValue;
        public BrushConverter(System.Windows.Media.Brush defaultValue)
        {
            this.defaultValue = defaultValue;
        }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Style.Brush uitValue = value as Style.Brush;
            System.Windows.Media.Brush result;
            if (uitValue == null)
                return defaultValue;
            result = Convert(uitValue as Style.SolidColorBrush);
            if (result != null)
                return result;
            result = Convert(uitValue as Style.RadialGradientBrush);
            if (result != null)
                return result;
            throw new NotSupportedException();
        }

        private System.Windows.Media.Brush Convert(Style.RadialGradientBrush brush)
        {
            if (brush == null)
                return null;
            var result = new System.Windows.Media.RadialGradientBrush();
            result.GradientOrigin = new System.Windows.Point(brush.GradientOrigin.X, brush.GradientOrigin.Y);
            foreach (var gradientStop in brush.GradientStops)
            {
#if !SILVERLIGHT
                result.GradientStops.Add(new System.Windows.Media.GradientStop(ColorConverter.Convert(gradientStop.Color), gradientStop.Offset));
#else
                result.GradientStops.Add(new System.Windows.Media.GradientStop() { Color = ColorConverter.Convert(gradientStop.Color), Offset = gradientStop.Offset });
#endif
            }
            return result;
        }

        private System.Windows.Media.Brush Convert(Style.SolidColorBrush brush)
        {
            if (brush == null)
                return null;
            return new System.Windows.Media.SolidColorBrush() { Opacity = brush.Opacity * 0.01, Color = ColorConverter.Convert(brush.Color) };
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
